from __future__ import absolute_import
import logging
from forest.api import Command, get_tool, get_md5
from os.path import join, dirname, exists

logger = logging.getLogger('forest.files.copy')

class Copy(Command):
    ''' Copies files to the install root, as per file resource specification.
    '''
    __register__ = 'commands.files.Copy'

    def run(self, config):
        install_tree = config.get_install_root()

        for file in config.get_resources().iter_by_type('file'):

            dst = file.get_path()
            file_url = file.get_url()
            logger.debug('Copy of File resource (%s) in %s. ',  dst, file.get_config().get_filename())

            dst = join(install_tree, *dst.split('/'))
            dst_md5 = get_md5(dst)

            if exists(dst) and file.get_md5() == dst_md5:
                logger.info('Skipping file of %s to %s (identical).', file_url, dst)
                continue


            logger.info('Copying from %s to %s', file_url, dst)

            # create the destination directory if necessary
            get_tool('system.mkdir')(dirname(dst))

            # TODO: exclusive check if needs a mode update
            try:
                get_tool('system.copy')(file.get_content(), dst, file.get_mode())
            except MissingFileError as e:
                logger.debug(e)

            # notify later commands of modified files
            config.add_modified(dst)


